package com.jiaai.util;


import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 *
 * </p>
 * @title  ${}
 * @author 佳爱网络科技
 * @version V1.0
 * @since 2017-7-10
 */
public class WeiXinUtil {
    private static  final  String OAUTH2=" https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
//    https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
	private static Logger log= LoggerFactory.getLogger(WeiXinUtil.class);
	private static final String APP_WXINFO = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
	/**
	 * 获取授权连接
	 * @param appId
	 * @return
	 */
	public static String getOpenid(String appId,String code,String secret){
        String url=OAUTH2.replace("APPID",appId).replace("SECRET",secret).replace("CODE",code);
        log.error(url);
		JSONObject jsonObject = HttpClientUtil.httpsRequest(url, "GET", null);
		log.error(jsonObject.toJSONString());
		return jsonObject.getString("openid");

	}
	/**
	 * 获取授权连接
	 * @param appId
	 * @return
	 */
	public static JSONObject getJSON(String appId,String code,String secret){
		String url=OAUTH2.replace("APPID",appId).replace("SECRET",secret).replace("CODE",code);
		log.error(url);
		JSONObject jsonObject = HttpClientUtil.httpsRequest(url, "GET", null);
		log.error(jsonObject.toJSONString());
		return jsonObject;

	}

	/**
	 * 通过openId获取用户信息
	 * @param openId
	 * @return
	 */
	public static JSONObject getUserInfoByOpenId(String openId, String accessToken )throws Exception{
		//"https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
		String apiUrl=APP_WXINFO.replace("ACCESS_TOKEN", accessToken);
		apiUrl=apiUrl.replace("OPENID", openId);
		JSONObject jsonObject= HttpClientUtil.httpsRequest(apiUrl, "GET", null);
//		if(jsonObject.containsKey("errcode")||jsonObject.getString("subscribe").equals("0")){
//			throw new Exception("获取用户信息失败:"+jsonObject.toJSONString());
//		}
		return jsonObject;
	}

}
